#!/usr/bin/env python
# -*- coding:utf-8 -*-

""" 
@author: zhaoqifa@baidu.com
@license: Copyright (c) 2013 Baidu.com, Inc. All Rights Reserved
"""

import os
import re
from lib.log import GLog

class ConfigManager():
    ''' the class for configuration translation and load '''
    def __init__(self,name=None):
        self.kv_dict = {}
        self.set_default_conf()
        self.name = name

    def set_default_conf(self):
        pass
        
    def read_conf(self,conf_path,SEP="="):
        if not os.path.exists(conf_path):
            GLog.warning("Configure file[%s] does not exist!",conf_path)
            return 1
        section = None
        section_pattern = re.compile(r"^\s*\[\s*(\w+)\s*\]\s*$")
        ret = 0
        with open(conf_path,"r") as infile:
            for line in infile:
                line = line.strip()
                if len(line) == 0 or line.startswith("#"):
                    continue
                matched = re.match(section_pattern,line)
                if matched is not None:
                    section = matched.groups()[0]
                else:
                    content_comments_pair=line.split("#",1) #to deal with content like "a=1 #set a as 1"
                    ret += self.read_key_value(section,content_comments_pair[0],SEP)
        return ret

    def read_key_value(self,section,line,SEP):
        GLog.debug("read basic conf[%s]",line)
        kv_pair = line.split(SEP,1)
        key = kv_pair[0].strip()
        if len(kv_pair) >= 2:
            value = kv_pair[1].strip()
        else:
            value = None
        return self.set(key,value,section)
        
    def get(self,key,section=None,default=None):
        if section in self.kv_dict:
            if key in self.kv_dict[section]:
                return self.kv_dict[section][key]
        GLog.debug("Key[%s] in section[%s] not found in ConfigManager",key,section)
        return default

    def get_section(self,section=None):
        if section in self.kv_dict:
            return self.kv_dict[section]
        return {}
        
    def set(self,key,value,section=None):
        if section not in self.kv_dict:
            self.kv_dict[section]={}
        self.kv_dict[section][key] = value
        return 0

    def get_original_dict(self):
        return self.kv_dict

